<template>
  <div id="personalaccount" class="doctor-container">
    <NavBar></NavBar>
    <!-- <sys-notice></sys-notice> -->
    <div class="personalaccount-container">
      <div class="head-content">
        <div class="left">
          <div class="title">{{ getUserName() }}医生，欢迎登录融影标注系统！</div>
          <div class="sub-title">感谢您对人工智能医疗研究的付出。</div>
        </div>
        <div class="right">
          <img :src="ill" />
        </div>
      </div>

      <div class="current-task-container">
        <div class="text-info">
          <div class="left">
            <span class="sub-text">进行中的任务：</span>
            <span class="sub-text-tip">
              <el-icon><Warning /></el-icon>
              下面仅列出最新5个，查询全部请点击右侧按钮
            </span>
          </div>
          <div>
            <el-button type="primary" :icon="Search" @click="handleShowTask"
              >已领取任务</el-button
            >
            <el-button type="primary" :icon="Plus" @click="handleAddTask"
              >领取新任务</el-button
            >
          </div>
        </div>
        <div class="current-task-list">
          <div
            v-for="item in currentTaskList"
            :key="item.id"
            @click="goDetail(item.id)"
            :class="!!item.userUnSubmmitSeriesCount ? 'task-block is-tip' : ' task-block'"
          >
            <div class="task-title" :title="`${item.id}-${item.name}`">
              {{ item.id }}-{{ item.name }}
            </div>
            <div class="task-infos">
              <div class="info">
                可领取序列/总序列：
                {{ `${item.enableGetSeriesCount}/${item.totalSeriesCount}` }}
              </div>
              <div class="info">
                任务截止日期： {{ formatDateTime(item.taskEndDate) }}
              </div>
              <div class="info-small">
                {{ !!item.userUnSubmmitSeriesCount ? "名下存在未提交序列" : "" }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="history-task-container">
        <div class="text-info">所有任务</div>
        <div class="search-container">
          <div class="search-input">
            <el-input
              v-model="model.keyword"
              placeholder="任务ID/名称"
              :prefix-icon="Search"
              style="width: 272px; margin-right: 24px"
              clearable
              @keyup.enter.native="search"
            />
            <el-select
              v-model="model.status"
              style="width: 200px"
              placeholder="任务状态"
              clearable
            >
              <el-option
                v-for="item in taskStatusList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="buttons-container">
            <el-button @click="reset">重置</el-button>
            <el-button @click="search" type="primary">查询</el-button>
          </div>
        </div>
        <Table
          :columns="[
            { title: '任务ID', dataIndex: 'id' },
            { title: '任务名称', dataIndex: 'name' },
            { title: '任务状态', dataIndex: 'status', slotName: 'status' },
            {
              title: '我参与的/总序列数',
              dataIndex: 'userGettedSeriesCount',
              slotName: 'userGettedSeriesCount',
            },
          ]"
          :data="allTastList"
          :total="allTaskTotal"
          :current="currentPage"
          :pageSize="pageSize"
          :scroll="scroll"
          :scrollbar="true"
          :stickyHeader="true"
          :showPageSize="true"
          @handle-size-change="handleCurrentChange"
          @handle-current-size-change="handleSizeChange"
          @handle-row-click="handleRowClick"
        >
          <template #status="{ record, column, index }">
            <span>{{
              (taskStatusList.find((item) => item.value == record.status) || {}).name ||
              ""
            }}</span>
          </template>
          <template #userGettedSeriesCount="{ record, column, index }">
            <span>{{
              `${record.userGettedSeriesCount}/${record.totalSeriesCount}`
            }}</span>
          </template>
        </Table>
      </div>
    </div>
    <NewTaskList
      v-model:visible="newTaskListVisible"
      :currnetIds="currnetIds"
      @on-change="selectChange"
    ></NewTaskList>
    <doingTaskModal v-model:visible="doingTaskVisible"></doingTaskModal>
  </div>
</template>

<script lang="ts" setup>
//@ts-noCheck
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
// import router from '@/router';
// import SysNotice from '@/components/sys-notice/index.vue';
import NavBar from "@/components/navbar/index.vue";
import ill from "@/assets/images/ill.png";
import { Plus, Search } from "@element-plus/icons-vue";
import { formatDateTime } from "@/utils/date";
import NewTaskList from "@/views/doctor/components/NewTaskList.vue";
import doingTaskModal from "@/views/doctor/components/doingTaskModal.vue";
import Table from "@/components/table/index.vue";
import { queryDoingTask, taskJoin, userTaskSearch } from "@/api/doctor/doctor";
import { UserTaskSearchModel } from "@/api/doctor/doctor.d";
import { ElMessageBox } from "element-plus";

const router = useRouter();

const getUserName = () => {
  const userInfo = localStorage.getItem("user") || "";
  return userInfo ? JSON.parse(userInfo)?.userName : "";
};

onMounted(async () => {
  setCurrentTaskList();
  setTaskListInfo();
});
const scroll = {
  x: "100%",
  y: "100%",
};

const currentTaskList = ref([]);

async function setCurrentTaskList() {
  const param = { page: 1, pageSize: 5 };
  const {
    data: { list, pages, total },
  } = await queryDoingTask(param);
  currentTaskList.value = list || [];
}

/**
 * 所有任务 搜索
 */
const taskStatusList = reactive([
  { name: "未发布", value: 0 },
  { name: "进行中", value: 1 },
  { name: "已完成", value: 2 },
  { name: "已终结", value: 3 },
]);
const model = reactive({
  keyword: null,
  status: null,
  page: 1,
  pageSize: 10,
});
const reset = () => {
  model.keyword = null;
  model.status = null;
  model.page = 1;
  model.pageSize = 10;
  setTaskListInfo(model);
};
const search = () => {
  setTaskListInfo({
    keyword: model.keyword,
    status: model.status,
  });
};
const allTastList: any = ref([]);

async function setTaskListInfo(opt: any = {}) {
  const model: UserTaskSearchModel = {
    page: opt.page || currentPage.value,
    pageSize: opt.pageSize || pageSize.value,
    keyword: opt.keyword || "",
    taskStatus: opt.status || "",
  };
  const res = await userTaskSearch(model);
  allTastList.value = res.data.list || [];
  allTaskTotal.value = res.data.total || 0;
}

/**
 * 分页
 */
const allTaskTotal = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const handleSizeChange = (size) => {
  pageSize.value = size;
  setTaskListInfo({
    pageSize: size,
    keyword: model.keyword,
  });
};
const handleCurrentChange = (page) => {
  currentPage.value = page;
  console.log(page);
  setTaskListInfo({
    page: page,
    keyword: model.keyword,
    status: model.status,
  });
};
const handleRowClick = (row) => {
  console.log(row, "row");
  goDetail(row.row.id);
};

/**
 * 领取新任务
 */
const newTaskListVisible = ref(false);
const currnetIds = computed(() => currentTaskList.value.map((item: any) => item.id));
const handleAddTask = () => {
  newTaskListVisible.value = true;
};

async function selectChange(values) {
  const model = {
    taskIds: values.map((item) => item.id),
  };
  // currentTaskList.value.push(...values);
  const res:any = await taskJoin(model);
  if(res && (res.code === 200)){
    if (values.length) {
      ElMessageBox.confirm("是否立即开始?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        go(values[0]?.imageLayout, "create", values[0]?.id);
      });
    }
  }
  await setCurrentTaskList();
}

const goDetail = (id) => {
  router.push({
    path: "/doctor/doctorDetail",
    query: {
      taskId: id,
    },
  });
};
//已领取任务
const doingTaskVisible = ref(false);
const handleShowTask = () => {
  doingTaskVisible.value = true;
};
const go = (pageType: string, type: string, taskId: number) => {
  const jumpPage = {
    MPR_ANNO: "mpr",
    MPATHOLOGYPR_ANNO: "bigPicture",
    VIDEO_ANNO: "video",
  };
  router.push({
    path: `/${jumpPage[pageType]}`,
    query: {
      id: taskId,
      type,
    },
  });
};
</script>

<style lang="less" scoped>
@basicColor: #448e97;
.doctor-container {
  // height: 100%;
  height: calc(100vh - 56px);
  padding: 20px;
  position: relative;
  top: 56px;

  .personalaccount-content-fade {
    background: #f9f9f9;
  }

  .personalaccount-container {
    position: relative;
    color: #333;
    height: 100%;

    .text-info {
      display: flex;
      justify-content: space-between;
      font-size: 20px;
      margin-bottom: 23px;

      .left {
        display: flex;
        align-items: center;

        .sub-text {
          font-style: normal;
          font-weight: 700;
          font-size: 16px;
          color: #333333;
        }

        .sub-text-tip {
          display: flex;
          align-items: center;
          font-size: 12px;
          color: #999999;
          margin-left: 12px;
        }
      }
    }

    .head-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 126px;
      margin-bottom: 16px;
      background-color: #fff;
      padding: 28px 40px;
      box-sizing: border-box;

      .left {
        .title {
          font-weight: 700;
          font-size: 28px;
          color: #448e97;
        }

        .sub-title {
          font-size: 16px;
          color: #666;
          margin-top: 12px;
        }

        .number {
          color: @basicColor;
          font-weight: bold;
        }
      }

      .right {
        img {
          width: 334px;
        }
      }
    }

    .current-task-container {
      background-color: #fff;
      padding: 20px;
      margin-bottom: 16px;

      .current-task-list {
        display: flex;
        align-items: center;
        width: 100%;

        .task-block {
          display: flex;
          flex-direction: column;
          width: ~"calc(20% - 8px)";
          // height: 150px;
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          margin-right: 8px;
          cursor: pointer;

          &.is-tip {
            .task-title {
              background: #ffe2c1;
            }
          }

          &:hover {
            box-shadow: 0 0 4px 2px rgba(68, 142, 151, 0.2);
          }

          .task-title {
            width: 100%;
            font-size: 16px;
            padding: 0 16px;
            line-height: 46px;
            background: #fafafa;
            border-bottom: 1px solid #d9d9d9;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .task-infos {
            padding: 20px;
          }

          .info {
            font-size: 14px;
            color: #666;
            margin-bottom: 16px;
          }

          .anno-last-update-time {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .info-small {
            height: 14px;
            margin-top: 30px;
            font-size: 12px;
            color: #ff8800;
          }
        }
      }
    }

    .history-task-container {
      background-color: #fff;
      padding: 20px;
      height: calc(100% - 415px);
      overflow-y: auto;

      .text-info {
        font-size: 16px;
        color: #333;
        font-style: normal;
        font-weight: 700;
      }

      .search-container {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        .buttons-container {
          background-color: #fff;
        }
      }

      :deep(.table-container) {
        height: calc(100% - 135px);
        min-height: 179px;
        .arco-table {
          height: calc(100% - 46px);
          .arco-table-content {
            .arco-table-header {
              background-color: white;
            }

            .arco-table-body {
              background-color: white;
            }
          }
        }
        // .arco-table {
        //   .arco-table-content {
        //     .arco-table-header {
        //       background-color: white;
        //     }

        //     .arco-table-body {
        //       background-color: white;
        //     }
        //   }
        // }
      }

        //     .arco-table-body {
        //       background-color: white;
        //     }
        //   }
        // }
      }
    }
  }
</style>
